package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;

    /**
     * 发送验证码并保存
     * @param phone
     * @param session
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        // 随机生成验证码(引用 hutool 工具类)
        String code = RandomUtil.randomNumbers(6);
/*        // 保存验证码到session
        session.setAttribute("code", code);*/
        // 保存验证码到 redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 发送验证码
        log.info("验证码发送成功：{}", code);
        return Result.ok();
    }

    /**
     * 用户登录
     * @param loginForm
     * @param session
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            throw new RuntimeException("手机号格式错误");
        }
        // 校验验证码
        String code = loginForm.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
        if (cacheCode == null || !cacheCode.equals(code)) {
            throw new RuntimeException("验证码错误");
        }
        // 是否为新用户
        String phone = loginForm.getPhone();
        User user = userMapper.selectUser(phone);
        if (user == null) {
            // 如果是新用户，存入数据库
            user = createUser(phone);
        }
        // 保存用户到 redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 用 hutool 将 DTO 封装为 Map 类型
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(false) // 即使是 null 也保存
                        .setFieldValueEditor((fieldName, fieldValue) -> {
                            if (fieldValue == null) {
                                return "";
                            }
                            return fieldValue.toString(); // Long 等类型也能安全转 String
                        }));
        // 生成用户 UUID 作为 token登录令牌
        String token = UUID.randomUUID().toString(true);
        // 存储
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        // 设置 token 有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 登录
        return Result.ok(token);
    }

    /**
     * 创建新用户
     * @param phone
     * @return
     */
    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.addNewUser(user);
        return user;
    }

    /**
     * 查看博主主页
     * @param id
     * @return
     */
    @Override
    public Result selectUser(Long id) {
        User user = userMapper.getUser(id);
        if(user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        // 获取当前用户
        Long id = UserHolder.getUser().getId();
        // 拼接 key
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + id + keySuffix;
        // 为当天进行签到
        int dayOfMonth = now.getDayOfMonth() - 1;
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);

        return Result.ok();
    }

    /**
     * 统计连续签到天数
     * @return
     */
    @Override
    public Result countSign() {
        // 获取当前用户
        Long id = UserHolder.getUser().getId();
        // 拼接 key
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + id + keySuffix;
        // 获取当前日期
        int dayOfMonth = now.getDayOfMonth();
        // 获取本月签到视图  BITFIELD key [GET type offset] (返回的是十进制数字)
        List<Long> bitMap = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        // 没有签到结果返回 0
        if(bitMap == null || bitMap.isEmpty()) {
            return Result.ok(0);
        }
        Long num = bitMap.get(0);
        if(num == null || num ==0) {
            return Result.ok(0);
        }
        int count = 0;
        // 如果最后一位为 1，计数器 +1
        // 如果为 0，结束并返回结果
        while ((num & 1) == 1) {
            // 视图最后一位作位运算
            count++;
            num >>>= 1;
        }

        return Result.ok(count);
    }
}
